﻿var $ = jQuery.noConflict();

function commitChange(product_id) {
    loading();
    var no = $('#no_' + product_id).val();
    //var pri = $('#product_price_' + product_id).val();
    var dataResponse = { id: product_id };
    if (parseInt(no) > 0 ) { //&& parseInt(pri) > 0) {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(dataResponse),
            url: url_add_to_cart,
            dataType: "json",
            success: function (results) {
                if (typeof results != 'undefined' && typeof results != null) {
                    $('#countID').text("(" + results.split("|")[2] + ")");
                    $('#countID2').text("(" + results.split("|")[2] + ")");
                    $('#totalID').text(results.split("|")[1]);
                    var data = results.split("|")[0];
                    var con = parseInt(no) - 1;
                    $('#no_' + product_id).val(con);
                    var cart_sidebar = $("#cart-sidebar");
                    $("#cart-sidebar").html("");
                    var arr_from_json = JSON.parse(data);
                    var li_item = "";
                    $.each(arr_from_json, function (i, obj) {
                        li_item = li_item + "<li class='item' id='row-" + obj.record_id + "'>";
                        li_item = li_item + "<a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "' title='" + obj.product_name + "' class='product-image'><img src='" + obj.images + "' width='50' height='50' alt='" + obj.product_name + "' /></a>";
                        li_item = li_item + "<div class='product-details'>";
                        li_item = li_item + "<a title='Xóa khỏi giỏ hàng' onclick='removeFormCart(" + obj.count + ", " + obj.product_id + ", " + obj.record_id + ")' class='btn-remove'>Xóa khỏi giỏ hàng</a>";
                        li_item = li_item + "<p class='product-name'><a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "'>" + obj.product_name + "</a></p>";
                        li_item = li_item + "<strong id='product_count_" + obj.product_id + "'>" + obj.count + "</strong> x <span class='price'>" + set_price_text(obj.price) + "</span>";
                        li_item = li_item + "<input id='NoHidden" + obj.product_id + "' type='hidden' value='" + obj.quantity + "' />";
                        li_item = li_item + "</div>";
                        li_item = li_item + "</li>";
                    });
                    cart_sidebar.append(li_item);
                    OpenMiniCart();

                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                debugger;
            }
        }); 
    } else {
        loading();
        alert("Hiện sản phẩm đã hết hàng.Xin quí khách vui lòng lựa chọn sản phẩm khác.");
        return;
    }
    UnLoading();
}

function OpenMiniCart() {
    $.fancybox({
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 500,
        'speedOut': 300,
        'autoDimensions': true,
        'centerOnScroll': true,
        'width': '75%',
        'height': '75%',
        'autoScale': false,
        'href': '#cart_mini'

    });

    check_open_cart_button();
}

function set_price_text(va) {
    var result = "";
    if (typeof va != 'undefined' && typeof va != null && va != "" && va != "0") {
        result = va +" đ";
    }
    else {
        result = " Giá: liên hệ";
    }

    return result;
}

function check_open_cart_button() {
    var btn_cart_detail = $('#btn_cart_detail');
    var btn_check_out = $('#btn_check_out');
    var eli = $("#cart-sidebar").text();
    if ($.trim(eli).length <= 0) {
        if (typeof btn_cart_detail != 'undefined' && typeof btn_cart_detail != null) {
            btn_cart_detail.hide();
        }

        if (typeof btn_check_out != 'undefined' && typeof btn_check_out != null) {
            btn_check_out.hide();
        }
    }
    else {
        if (typeof btn_cart_detail != 'undefined' && typeof btn_cart_detail != null) {
            btn_cart_detail.show();
        }

        if (typeof btn_check_out != 'undefined' && typeof btn_check_out != null) {
            btn_check_out.show();
        }
    }
}

function removeFormCart(count, product_id, record_id) {
    if (!confirm('Bạn muốn xóa sản phẩm này khỏi giỏ hàng?')) {
        return false;
    }
    else {
        var dataResponse = { id: record_id };
        //loading();
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(dataResponse),
            url: url_remvove_from_cart,
            dataType: "json",
            success: function (results) {
                if (typeof results != 'undefined' && typeof results != null) {
                    $('#countID').text("(" + results.split("|")[2] + ")");
                    $('#countID2').text("(" + results.split("|")[2] + ")");
                    if (results.split("|")[1] == "0") { $('#totalID').text(""); } else { $('#totalID').text(results.split("|")[1]); }
                    var data = results.split("|")[0];
                    var no = $('#no_' + product_id).text();
                    var con = parseInt(no) + parseInt(count);
                    $('#no_' + product_id).val(con);
                    var cart_sidebar = $("#cart-sidebar");
                    $("#cart-sidebar").html("");
                    var arr_from_json = JSON.parse(data);
                    var li_item = "";
                    $.each(arr_from_json, function (i, obj) {
                        li_item = li_item + "<li class='item' id='row-" + obj.record_id + "'>";
                        li_item = li_item + "<a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "' title='" + obj.product_name + "' class='product-image'><img src='" + obj.images + "' width='50' height='50' alt='" + obj.product_name + "' /></a>";
                        li_item = li_item + "<div class='product-details'>";
                        li_item = li_item + "<a title='Xóa khỏi giỏ hàng' onclick='removeFormCart(" + obj.count + ", " + obj.product_id + ", " + obj.record_id + ")' class='btn-remove'>Xóa khỏi giỏ hàng</a>";
                        li_item = li_item + "<p class='product-name'><a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "'>" + obj.product_name + "</a></p>";
                        li_item = li_item + "<strong id='product_count_" + obj.product_id + "'>" + obj.count + "</strong> x <span class='price'>" + set_price_text(obj.price) + "</span>";
                        li_item = li_item + "<input id='NoHidden" + obj.product_id + "' type='hidden' value='" + obj.quantity + "' />";
                        li_item = li_item + "</div>";
                        li_item = li_item + "</li>";
                    });
                    cart_sidebar.append(li_item);

                    //disable row in cart detail
                    var row_record = $('#row-' + record_id);
                    if (typeof row_record != 'undefined' && typeof row_record != null) {
                        row_record.fadeOut('slow');
                    }

                    OpenMiniCart();


                    if (results.split("|")[2] == "0") {
                        var btnNext = $('#btn_next_checkout');
                        if (typeof btnNext != 'undefined' && typeof btnNext != null) {
                            btnNext.hide();
                        }
                    }
                    else {
                        var btnNext = $('#btn_next_checkout');
                        if (typeof btnNext != 'undefined' && typeof btnNext != null) {
                            btnNext.show();
                        }
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                debugger;
            }
        });
       // UnLoading();
    }
}

function HomeRedirect() { document.location = ""; }

function GetProductQuantityClient(quantity, product_id) {
    if (typeof quantity != 'undefined' && typeof quantity != null && typeof product_id != 'undefined' && typeof product_id != null) {
        if (parseInt(quantity) > 0) {
            var result = parseInt(quantity);
            var cart_list = $("#cart-sidebar");
            var record_count = cart_list.find("strong[id=product_count_" + product_id + "]").text();
            if (typeof record_count != 'undefined' && typeof record_count != null && record_count!= "") {
                result = result - parseInt(record_count);
            }
            return result;
        } else {
            return 0;
        }
        
    }  
}

function SetLoadProductQuantity() {
    loading();
    var listQuantity = new Array();
    listQuantity = $("#list_pro_qty").find("span[class='hidden_qty']"); 

    listQuantity.each(function () {
        var new_qty = GetProductQuantityClient($(this).attr('qty'), $(this).attr('id').split('_')[1]);
        $(this).text(new_qty);
    });
    UnLoading();
}

function checkNumberCart() {
    var eli = $("#cart-sidebar").text();
    if ($.trim(eli).length > 0) {
        window.location.href = "/gio_hang.ub"; 
    }
}

function go_to_check_out() {
    var eli = $("#cart-sidebar").text();
    if ($.trim(eli).length > 0) {
        window.location.href = '/dang_nhap_thanh_toan.ub';
    }
}

function UpdateCart() {
    var listQuantityInCart = new Array();
    var re_arr = new Array();
    var id_arr = new Array();
    var qty_arr = new Array();
    listQuantityInCart = $("#shopping-cart-table").find("input[pqty='input_quantity']");
    listQuantityInCart.each(function () {
        re_arr.push($(this).attr('record'));
        id_arr.push($(this).attr('id').split('_')[1]);
        qty_arr.push($(this).val());
    });

    var dataResponse = { id: re_arr + "|" + id_arr + "|" + qty_arr };
    if (re_arr.length > 0 && id_arr.length > 0 && qty_arr.length > 0 && re_arr.length == id_arr.length && re_arr.length == qty_arr.length) {
        loading();
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(dataResponse),
            url: url_update_cart,
            dataType: "json",
            success: function (results) {
                if (typeof results != 'undefined' && typeof results != null) {
                    //$('#countID').text("(" + results.split("|")[2] + ")");
                    if (results.split("|")[1] == "0") { $('#total_money').text(""); } else { $('#total_money').text(results.split("|")[1]); }
                    var data = results.split("|")[0];
                    var no = $('#no_' + product_id).val();
                    var con = parseInt(no) + parseInt(count);
                    $('#no_' + product_id).val(con);
                    var cart_sidebar = $("#cart-sidebar");
                    $("#cart-sidebar").html("");
                    var arr_from_json = JSON.parse(data);
                    var li_item = "";
                    $.each(arr_from_json, function (i, obj) {
                        li_item = li_item + "<li class='item' id='row-" + obj.record_id + "'>";
                        li_item = li_item + "<a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "' title='" + obj.product_name + "' class='product-image'><img src='" + obj.images + "' width='50' height='50' alt='" + obj.product_name + "' /></a>";
                        li_item = li_item + "<div class='product-details'>";
                        li_item = li_item + "<a title='Xóa khỏi giỏ hàng' onclick='removeFormCart(" + obj.count + ", " + obj.product_id + ", " + obj.record_id + ")' class='btn-remove'>Xóa khỏi giỏ hàng</a>";
                        li_item = li_item + "<p class='product-name'><a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "'>" + obj.product_name + "</a></p>";
                        li_item = li_item + "<strong id='product_count_" + obj.product_id + "'>" + obj.count + "</strong> x <span class='price'>" + set_price_text(obj.price) + "</span>";
                        li_item = li_item + "<input id='NoHidden" + obj.product_id + "' type='hidden' value='" + obj.quantity + "' />";
                        li_item = li_item + "</div>";
                        li_item = li_item + "</li>";
                    });
                    cart_sidebar.append(li_item);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                debugger;
            }
        });
        UnLoading();
    }
}

function checkemail(txt_email) {
    var test = $(txt_email).val();
    var dataResponse = { emailStr: test };
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(dataResponse),
        url: url_check_email,
        dataType: "json",
        success: function (results) {
            if (typeof results != 'undefined' && typeof results != null) {
                if (results == "1") {
                    $('#email_exists').text("");
                }
                else if (results == "0") {
                    $('#email_exists').text("Tài khoản email này đã được sử dụng.");
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            debugger;
        }
    });

}

function getOrderDetailHistory(order_id) {
    loading();
    var dataResponse = { id: order_id };
    if (parseInt(order_id) > 0) {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(dataResponse),
            url: url_order_detail_history,
            dataType: "json",
            success: function (results) {
                if (typeof results != 'undefined' && typeof results != null) {
                    var data = results;
                    var detail_history = $("#detail_history_" + order_id);
                    var total_price = $("#total_price_" + order_id);
                    var header = $("#header_" + order_id);
                    detail_history.html("");
                    total_price.html("");
                    header.html("");
                    var arr_from_json = JSON.parse(data);
                    var li_item = "";
                    var tot = "";
                    var tfoot = "";
                    var thead = "";
                    thead = thead + "<tr>";
                    thead = thead + "<th></th>";
                    thead = thead + "<th><strong>Tên sản phẩm</strong></th>";
                    thead = thead + "<th><strong>Giá</strong></th>";
                    thead = thead + "<th><strong>Số lượng</strong></th>";
                    thead = thead + "<th><strong>Giá hiện tại</strong></th>";
                    thead = thead + "</tr>";
                    header.append(thead);
                    $.each(arr_from_json, function (i, obj) {

                        li_item = li_item + "<tr id='row_" + obj.order_id + "'>";
                        li_item = li_item + "<td><a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "' title='" + obj.product_name + "' class='product-image'><img src='" + obj.images + "' width='50' height='50' alt='" + obj.product_name + "' /></a></td>";
                        li_item = li_item + "<td><a href='/san_pham/" + obj.product_alias + "_" + obj.product_id + "'>" + obj.product_name + "</a></td>";
                        li_item = li_item + "<td><strong>" + set_price_text(obj.price_value) + "</strong></td>";
                        li_item = li_item + "<td><strong>" + obj.quantity + "</strong></td>";
                        li_item = li_item + "<td><strong>" + set_price_text(obj.price) + "</strong></td>";
                        li_item = li_item + "</tr>";

                        tot = obj.total;
                    });
                    detail_history.append(li_item);
                    tfoot = tfoot + "<tr>";
                    tfoot = tfoot + "<td colspan='4'>Thành tiền:</td>";
                    tfoot = tfoot + "<td><strong>" + set_price_text(tot) + "</strong></td>";
                    tfoot = tfoot + "</tr>";
                    total_price.append(tfoot);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                debugger;
            }
        });
    } else {
        loading();
        return;
    }
    UnLoading();
}